<template>
  <div :class="{ 'hide-header': hideHeader, 'hide-title': hideTitle }">
    <div class="header">
      <span class="header-title">{{ nowDateTitle }}</span>
      <div class="header-right">
        <div class="icon" style="width: 20px;margin-right: 2px;" @click.stop="movePrev()">
          <i class="fa-solid fa-chevron-left"></i>
        </div>
        <div class="icon" style="width: 20px;margin-right: 2px;" @click.stop="moveNowDate()">
          <i class="fa-solid fa-o"></i>
        </div>
        <div class="icon" style="width: 20px;margin-right: 2px;" @click.stop="moveNext()">
          <i class="fa-solid fa-chevron-right"></i>
        </div>
      </div>
    </div>
    <v-date-picker v-model="date" :mode="mode" ref="datePickerRef" :view="view" :is-range="isRange" :rows="rows"
      :attributes="attributes" title-position="left" @dayclick="dayClick">

    </v-date-picker>
  </div>
</template>
<script>
export default {
  name: 'a-date-picker'
}
</script>
<script setup>
import { ref, onMounted, defineProps, defineExpose, defineEmits, watch } from 'vue'

const datePickerRef = ref(null)
const date = ref(new Date())
const props = defineProps({
  modelValue: {
    type: Date,
    default: new Date()
  },
  value: {
    type: Date,
    default: new Date()
  },
  mode: {
    type: String,
  },
  view: {
    type: String,
  },
  rows: {
    type: Number,
  },
  isRange: {
    type: Boolean,
  },
  hideHeader: {
    type: Boolean,
    default: false
  },
  hideTitle: {
    type: Boolean,
    default: false
  },
  attributes: {
    type: Array,
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'move'])

const nowDate = ref(new Date())
const nowDateTitle = ref('')

const dayClick = (e, event) => {
  emit('update:modelValue', e.date)
  emit('change', e.date, event)
}

// 日期格式化函数（补零）
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const formatDateTitle = () => {
  let date = nowDate.value
  if (props.view === 'weekly') {
    // 获取nowDate当前周的第一天 和 当前周的最后一天
    const startDate = getMondayOfCurrentWeek(date);
    const endDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + 6);
    if (startDate.getMonth() === endDate.getMonth()) {
      nowDateTitle.value = `${startDate.getFullYear()}年${startDate.getMonth() + 1}月`;
    } else if (startDate.getFullYear() === endDate.getFullYear()) {
      nowDateTitle.value = `${startDate.getFullYear()}年${startDate.getMonth() + 1}月 - ${endDate.getMonth() + 1}月`;
    } else {
      nowDateTitle.value = `${startDate.getFullYear().toString().substring(2, 4)}年${startDate.getMonth() + 1}月 - ${endDate.getFullYear().toString().substring(2, 4)}年${endDate.getMonth() + 1}月`;
    }
  } else {
    nowDateTitle.value = `${date.getFullYear()}年${date.getMonth() + 1}月`;
  }
};

function getMondayOfCurrentWeek(date) {
  const dayOfWeek = date.getDay(); // 获取今天是本周的第几天（0 是周日）
  const mondayDate = new Date(date); // 复制当前日期

  // 计算需要减去的天数，以得到最近的星期一
  const diffToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
  mondayDate.setDate(date.getDate() - diffToMonday);
  mondayDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

  return mondayDate;
}

const moveNowDate = () => {
  nowDate.value = new Date();
  date.value = nowDate.value
  datePickerRef.value.move(nowDate.value);
  formatDateTitle()
  emit('update:modelValue', nowDate.value)
  emit('change', nowDate.value, formatDate(nowDate.value))
  return nowDate.value;
}
const movePrev = () => {
  if (props.view === 'weekly') {
    nowDate.value.setDate(nowDate.value.getDate() - 7);
  } else {
    nowDate.value.setMonth(nowDate.value.getMonth() - 1);
  }
  moveToDate(nowDate.value)
  emit('move', nowDate.value, formatDate(nowDate.value))
  return nowDate.value;
}

const moveNext = () => {
  if (props.view === 'weekly') {
    nowDate.value.setDate(nowDate.value.getDate() + 7);
  } else {
    nowDate.value.setMonth(nowDate.value.getMonth() + 1);
  }
  moveToDate(nowDate.value)
  emit('move', nowDate.value, formatDate(nowDate.value))
  return nowDate.value;
}
const moveToDate = (_date) => {
  if (props.view === 'weekly') {
    datePickerRef.value.move({
      week: getWeekOfMonth(_date),
      month: _date.getMonth() + 1,
      year: _date.getFullYear(),
      date: _date.getDate(),
    });
  } else {
    datePickerRef.value.move(_date);
  }
  if (nowDate.value != _date) {
    nowDate.value = _date
    date.value = _date
  }
  formatDateTitle()
}


const getWeekOfMonth = (date) => {
  const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  const dayOfWeek = firstDay.getDay() || 7; // 周日为7
  const offset = dayOfWeek - 1;
  return Math.ceil((date.getDate() + offset) / 7);
};

watch(() => props.modelValue, (newVal) => {
  nowDate.value = newVal
  date.value = newVal
  formatDateTitle()
  datePickerRef.value.move({
    week: getWeekOfMonth(newVal),
    month: newVal.getMonth() + 1,
    year: newVal.getFullYear(),
  });
})

onMounted(() => {
  if (props.value) {
    date.value = new Date(props.value)
    nowDate.value = date.value
  } else {
    date.value = props.modelValue
    nowDate.value = date.value
  }
  formatDateTitle()
  moveToDate(date.value)
})

defineExpose({
  moveNext,
  moveToDate,
  movePrev
})
</script>
<style scoped lang="less">
/deep/ .vc-container {
  width: 100%;

  .vc-header {
    display: none;
  }

  .vc-pane-header-wrapper {
    display: none;
  }
}

.header {
  display: flex;
  align-items: center;
  margin: 6px;
  margin-top: 10px;
  transition: all 0.2s linear;

  .header-title {
    flex: 1;
    margin-left: 4px;
    text-align: left;
    font-size: 16px;
    font-weight: bold;
    color: var(--font-color);
  }

  .header-right {
    display: flex;

    .icon {
      text-align: center;
    }
  }
}

.hide-header {
  .header {
    margin: 0;
    padding: 0;
    opacity: 0;
    height: 0;
    overflow: hidden;
  }
}


.hide-title {
  /deep/ .vc-weekdays {
    opacity: 1;
    height: auto;
    transition: opacity 0.1s ease, height 0.1s ease;
  }

  /deep/ .vc-weekdays {
    opacity: 0;
    height: 0;
  }
}
</style>